Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Promises/await support #90

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open

Conversation

egormalyutin
Copy link

Added function deasync.await, that is like await in async function, but works in sync function or global scope.

function sleepAsync(time) {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			resolve()
		}, time)
	})
}
async function trim(str) {
	await sleepAsync(2000)
	return str.trim()
}

console.log(deasync.await(trim('       hello       ')))

index.js Outdated Show resolved Hide resolved
@NotWearingPants
Copy link

The throw inside the catch won't really throw outside

Comment on lines +80 to +94
done = false;
result = undefined;

pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})

deasync.loopWhile(() => { return !done });
return result;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
done = false;
result = undefined;
pr
.then(function(r) {
done = true;
return result = r;
})
.catch(function(err) {
done = true
throw err
})
deasync.loopWhile(() => { return !done });
return result;
done = false;
result = undefined;
error = undefined;
pr
.then(function(r) {
done = true;
result = r;
})
.catch(function(err) {
done = true;
error = err;
})
deasync.loopWhile(function() { return !done; });
if (error) throw error;
return result;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about errors what are falsy? for example Promise.reject(0) or Promise.reject(undefined).
This still would no throw an exception

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NotWearingPants I forgot that those rejections are technically possible. Indeed to cover that it would be better to use a didThrow variable instead.

@aminya aminya mentioned this pull request Dec 16, 2020
@loynoir
Copy link

loynoir commented Nov 10, 2021

deasync.await = p => deasync((cb)=>p.then(x=>cb(null,x),e=>cb(e,null)))()
> deasync.await(import('some-esm-module'))
[Module: null prototype] {
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants