3gw*_*ain 2 javascript asynchronous promise
我有2个功能.我正在用then()方法进行链接promise.但我试图second在第一个承诺发生后启动该功能.但现在第二个函数调用为第一个.怎么解决这个问题?
或者我的代码有什么问题?
这是我的尝试:
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 )));
Run Code Online (Sandbox Code Playgroud)
.then接受函数作为参数.当你这样做
.then(getDataMoreData()
.then((data) => console.log('data--', data))
);
Run Code Online (Sandbox Code Playgroud)
,它立即调用getDataMoreData()(期望它将返回一个可以放入promise链的函数).但是getDataMoreData不返回函数 - 它返回一个promise.
任何函数立即在get执行中立即调用then,因为它尝试构建.thenpromise链.只需列出函数变量then而不是调用它:
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));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |