简体   繁体   English

等待蓝鸟承诺解决,然后再继续

[英]Wait for Bluebird promise to resolve before continuing

I'm using an NPM package called snoowrap , that accesses the Reddit API. 我正在使用一个名为snoowrap的NPM软件包,该软件包可以访问Reddit API。 It returns results, such as from searches, as Bluebird promises. 它会返回Bluebird承诺的结果,例如来自搜索的结果。

I have file reddit.js like this: 我有这样的文件reddit.js

const snoowrap = require('snoowrap');

function getFirstSearchResultUrl() {
  // Actual Reddit API credentials not included.
  const r = new snoowrap({
    userAgent,
    clientId,
    clientSecret,
    username,
    password,
  });

  return r
    .search({
      query: 'query',
      subreddit: 'askreddit',
    })
    .then((posts) => {
      return posts[0].url;
    });
}

const resultUrl = getFirstSearchResultUrl();
console.log(resultUrl);

But console.log prints [chainable Promise] rather than the URL that is returned. 但是console.log打印[chainable Promise]而不是返回的URL。

How can I get it to print the URL that was returned, instead of the promise? 我如何获得它来打印返回的URL,而不是诺言? I looked through the docs and tried different Bluebird methods like .reflect() and .settle() but they didn't seem to work for me. 我通过文档看去,尝试了不同的蓝鸟方法,如.reflect().settle()但他们似乎并没有为我工作。

Is it possible to prevent the rest of the script from executing until the promise is completed? 是否可以阻止脚本的其余部分在promise完成之前执行?

Your getFirstSearchResultUrl() returns a promise. 您的getFirstSearchResultUrl()返回一个Promise。 That's why you see that log statement printed. 这就是为什么您看到该日志语句的原因。 And promise is not resolved yet. 承诺尚未解决。

So,You can wait for it to resolve with async/await or you can log the returned results adding a callback to .then() with getFirstSearchResultUrl() . 因此,您可以等待它通过async/await解析,也可以记录返回的结果,并使用getFirstSearchResultUrl().then()添加回调。

Something like getFirstSearchResultUrl().then(url=> console.log(url)) 类似于getFirstSearchResultUrl().then(url=> console.log(url))

You can also await for your getFirstSearchResultUrl() to be resolved, get the results and log it 您也可以await getFirstSearchResultUrl()得到解决,获取结果并记录下来

Something like 就像是

(async function(){
  var url  =  await getFirstSearchResultUrl();
  console.log(url);
})(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM