簡體   English   中英

返回 new Promise() 在 Node.js 中不起作用

[英]return new Promise() not working in Node.js

我對 Promise 的概念以及一般的 JavaScript 都不熟悉。 我正在嘗試在 Node.js 中編寫一個函數,我可以將 URL 傳遞給結果的承諾。

我以兩種方式對其進行了編程。 第一個不起作用,我可以將 URL 傳遞給函數。 第二個確實有效,其中 URL 是靜態定義的。 第一個不起作用,因為編譯器出於某種我無法弄清楚的原因認為它不是一個函數,為什么?

這種方式不起作用,因為函數getJson不被 Node 解釋為函數:

var options = { method: 'GET',
                url: URL,  // This will be dynamically filled by the argument to the function getJson
                headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = function(URL){

  return new Promise(function(resolve, reject) {

    request(options, function (error, response, body) {
      if(error) reject(error);
      else {
        resolve(JSON.parse(body));  //The body has an array in the jason called Items 
      }
    });
  });  // Edited original post. Had two curly braces }}; here by accident, which was why function was not being recognized
};  

getJson.then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

這種方式行之有效,我將一系列物品返回到控制台。 這樣做的缺點是使用的 URL 是靜態的。 我想要做的重點是通過獲取 API 的結果鏈接一堆 URL,一個 URL 調用然后包含 NextPage 結果的 URL。

var options = { method: 'GET',
  url: 'http://staticURL',
  headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = new Promise(function(resolve, reject) {
  request(options, function(err, response, body) {
    if(err) reject(err);
    else {
      resolve(JSON.parse(body));
    }
  });
});

getJson.then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

試試這個:

var getJson = function(URL){
  var options = { 
    method: 'GET',
    url: URL,
    headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } 
  };
  return new Promise(function(resolve, reject) {

    request(options, function (error, response, body) {
      if(error) reject(error);
      else {
        resolve(JSON.parse(body));
      }
    });
  }};
};  

然后你可以調用它:

getJson(theDynamicURLGoesHere).then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});
getJson.then(...)

在您的第一個代碼塊中是不正確的。 它必須是:

getJson(someURL).then(...)

因為在第一個代碼塊中, getJson是一個函數,因此您必須調用它來執行它,並且需要向它傳遞所需的參數。


在您的第一個代碼塊中, getJson是一個函數,它在您調用和執行該函數時返回一個承諾,因此您必須調用該函數才能獲得該承諾。 在第二個代碼塊中, getJson 已經是一個 promise,因此您可以調用getJson.then(...)

getJson()是一個函數,所以你需要用()調用它:

getJson(URL).then(onFulfilled, onRejected);

需要注意的重要一點是,promise 是一個對象,您可以使用構造函數創建一個新的 promise 不要嘗試將承諾用作函數 - 承諾立即開始執行, .then()只是注冊一個事件處理程序,以便在承諾更改狀態時通知您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM