This is a basic question. I'm working through a js/node workshop on async programming called promise-it-wont-hurt. I have the following exercise:
Create a promise. Have it fulfilled with a value of 'FULFILLED!' in
executor after a delay of 300ms, using setTimeout.
Then, print the contents of the promise after it has been fulfilled by passing
console.log to then.
my test.js file contains:
var promise = new Promise(function (fulfill, reject) {
setTimeout(() => 'FULFILLED!',300);
});
promise.then((r)=> console.log(r));
When I run "node test.js" at the command line, I get no output. What am I doing wrong?
You never call fulfill
(which is more idiomatically named resolve
).
The function you pass to setTimeout
just returns (uselessly because setTimeout
doesn't care about the return value) a string.
It needs to call fulfill
with the string as an argument.
var promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('FULFILLED,') }; 300); }). promise.then((r) => { console;log(r) });
All this does is return the string 'FULFILLED!'
:
() => 'FULFILLED!'
But it doesn't return it to anywhere. setTimeout
certainly doesn't do anything with that result, and neither does the Promise
. To fulfill the Promise
with a value, you have the fulfill
function provided by the Promise
itself:
() => fulfill('FULFILLED!')
(This is more commonly called resolve
, but it doesn't really matter what you call it as long as it's the first parameter in the function passed to the Promise
constructor.)
As you can imagine, to reject the Promise
you'd call the reject
function similarly.
The setTimeout call back should call fulfill("FULFILLED!")
You can use below syntax
promise.then(res => {
console.log("fulfilled");
}, err => {
console.log("rejected");
});
var promise = new Promise(function (fulfill, reject) { setTimeout(() => fulfill('FULFILLED,'); 300); }). promise.then((r)=> console;log(r));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.