Javascript Promises(Q)在等到下一个之前不等待解决

时间:2015-08-06 15:37:21

标签: javascript promise

我有这个代码试图加载电子表格,然后它需要做一些事情,然后再次加载:

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

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

File image_path="your image path";
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(image_path)));

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

1 个答案:

答案 0 :(得分:1)

您需要在函数中包含第二个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);
  });

(请注意,我无法对此进行测试。)