gpt4 book ai didi

Javascript Promises (Q) 不会等待解决后再进行下一个

转载 作者:行者123 更新时间:2023-11-28 00:00:25 25 4
gpt4 key购买 nike

我有这段代码正在尝试加载电子表格,然后需要执行某些操作,然后再次加载:

var Q = require('q'),
editGoogleSpreadsheet = require('edit-google-spreadsheet');


loadSpecificSheet = function(_spreadsheetName, _worksheetName) {
return Q.ninvoke(editGoogleSpreadsheet, 'load', {
debug: true,
spreadsheetName: _spreadsheetName,
worksheetName: _worksheetName,
oauth: {
email: superSecretEmail,
keyFile: superSecretKeyfile
}
});
};


google.loadSpecificSheet(spreadsheetName, worksheetName).then(
function(spreadsheet) {
console.log("loaded")
},
function(err) { node.warn("sheet failed to load: " + err); }
).then(
google.loadSpecificSheet(spreadsheetName, worksheetName).then(
function(spreadsheet) {
console.log("loaded 2")
},
function(err) { node.warn("sheet failed to load 2: " + err); }
)
).catch(function(err) { node.warn("ToGoogleSheetNode Error: " + err); });

console.log("promises added to queue");

但是,它同时加载电子表格两次,如调试中所示:

promise added to queue
Logging into Google...
Logging into Google...
Logged into Google
Searching for Spreadsheet 'Book1'...
Logged into Google
Searching for Spreadsheet 'Book1'...
Searching for Worksheet 'Sheet1'...
Searching for Worksheet 'Sheet1'...
loaded 2
loaded

为什么链中的第二个 Promise 不等待链中的第一个 Promise?我需要它等待...

最佳答案

您需要将第二个 load 调用包装在函数中,并从 .then() 回调中正确返回值:

google.loadSpecificSheet(spreadsheetName, worksheetName)
.then(
function(spreadsheet) {
console.log("loaded");
return spreadsheet;
},
function(err) { node.warn("sheet failed to load: " + err); }
)
.then(function() {
return google.loadSpecificSheet(spreadsheetName, worksheetName)
})
.then(
function(spreadsheet) {
console.log("loaded 2");
},
function(err) { node.warn("sheet failed to load 2: " + err); }
)
.catch(function(err) {
node.warn("ToGoogleSheetNode Error: " + err);
});

(请注意,我无法真正测试这一点。)

关于Javascript Promises (Q) 不会等待解决后再进行下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com