这是一个基本问题。我正在参加一个关于异步编程的 js/node 研讨会,称为 promise-it-wont-hurt。我有以下练习:
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.
我的 test.js 文件包含:
var promise = new Promise(function (fulfill, reject) {
setTimeout(() => 'FULFILLED!',300);
});
promise.then((r)=> console.log(r));
当我在命令行运行“node test.js”时,我没有得到任何输出。我做错了什么?
答案 0 :(得分:1)
您从不调用 fulfill
(它更符合惯用的名称 resolve
)。
您传递给 setTimeout
的函数只是返回(无用,因为 setTimeout
不关心返回值)一个字符串。
它需要以字符串作为参数调用 fulfill
。
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('FULFILLED!')
}, 300);
});
promise.then((r) => {
console.log(r)
});
答案 1 :(得分:1)
所做的只是返回字符串 buildozer
:
'FULFILLED!'
但它不会将它返回到任何地方。 () => 'FULFILLED!'
当然不会对这个结果做任何事情,setTimeout
也不会。要使用值实现 Promise
,您需要 Promise
本身提供的 fulfill
函数:
Promise
(这更常见地称为 () => fulfill('FULFILLED!')
,但您怎么称呼它并不重要,只要它是传递给 resolve
构造函数的函数中的第一个参数即可。)
如您所想,要拒绝 Promise
,您可以类似地调用 Promise
函数。
答案 2 :(得分:1)
setTimeout 回调应该调用 fulfill("FULFILLED!")
答案 3 :(得分:1)
您可以使用以下语法
promise.then(res => {
console.log("fulfilled");
}, err => {
console.log("rejected");
});
答案 4 :(得分:0)
var promise = new Promise(function (fulfill, reject) {
setTimeout(() => fulfill('FULFILLED!'), 300);
});
promise.then((r)=> console.log(r));