问题描述
我确实有2个功能.我与 promise
的 then()
方法链接.但是我试图在第一个承诺发生后启动 second
函数.但是现在第二个函数调用成为第一个.该如何解决?
I do have 2 function. I am chaining with then()
method for promise
. But I am trying to initiate the second
function after the first promise happend. But now the second function call as first. how to fix this?
或者我的代码有问题吗?
or any issue with my code?
这是我的尝试:
var getData = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(42); //consoles as second
}, 5000);
})
}
var getDataMoreData = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(43); //consoles as first
}, 3000);
})
}
getData().then((data)=> console.log('Data', data)).then(getDataMoreData().then((data)=> console.log('data--', data )));
推荐答案
.然后
接受 function 作为参数.当你做
.then
accepts a function as a parameter. When you do
.then(getDataMoreData()
.then((data) => console.log('data--', data))
);
,它立即调用 getDataMoreData()
(期望它会返回可以放入promise链中的函数).但是 getDataMoreData
不会返回一个函数-它会返回一个Promise.
, it immediately calls getDataMoreData()
(with the expectation that it will return a function that it can put into the promise chain). But getDataMoreData
does not return a function - it returns a promise.
任何函数立即在 then
中调用,因为它试图构建 .then
承诺链.只需在 then
内列出函数变量,而不用调用它:
Any function calls immediately within a then
get executed immediately, as it attempts to build the .then
promise chain. Simply list the function variable inside the then
instead of calling it:
var getData = function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(42);
}, 500);
})
}
var getDataMoreData = function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(43);
}, 300);
})
}
getData()
.then((data) => console.log('Data', data))
.then(getDataMoreData)
.then((data) => console.log('data--', data));
这篇关于答应-`then()`不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!