0

我在节点中,我有一个 obj 数组{suggestion: 'text', rank: '2'},我想用它来调用 bing 以获得每个对象的第一个结果。

目前,我已经使用Promise.all

await Promise.all(suggestions.map(async (s, i) => await bingWebSearch(s.suggestion.replace(/\s/g, '+'), i)))
    .then(r => {
      suggestions.map((s, i) => console.log(`
      n${i+1}. ${s.suggestion} | times suggested: ${s.rank} | url: ${s.webpage}
      `))
  })
    .catch(e => e.message)

这将调用函数 bingWebSearch 并将网站 URL 分配给 obj

const bingWebSearch = async (query, i) => {
 
    return await axios.get('https://api.bing.microsoft.com/v7.0/search?', {
      headers: {
        'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY
      },
      params: {
        count: 1,
        mkt: 'en-US',
        q: query
      }
    }).then(r => {
      if (r.data.webPages) return suggestions[i].webpage = r.data.webPages.value[0].url
    }).catch(e => console.log(e.message))
  }

所以基本上,这将触发 30 次对 bing 的调用,但我只能做 3/秒我怎样才能实现它?我尝试过使用 setTimeOut,但使用异步函数有点棘手,所以它不起作用。

4

1 回答 1

0

这是我的建议:

function delay(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}

const bingWebSearch = (query, ms) => {
  return new Promise((resolve, reject) => {
    delay(ms).then(() => {
      axios
        .get("https://api.bing.microsoft.com/v7.0/search?", {
          headers: {
            "Ocp-Apim-Subscription-Key": SUBSCRIPTION_KEY
          },
          params: {
            count: 1,
            mkt: "en-US",
            q: query
          }
        })
        .then(r => {
          resolve(r.data.webPages.value[0].url);
        })
        .catch(e => {
          console.log(e.message);
          // this will just return an empty string as a result, if something goes wrong
          resolve("");
          // you can also reject and handle the exception inside calling for loop
          // if more advanced error handling is required
          // reject(e);
        });
    });
  });
};

async function load() {
  const requests = suggestions.map((s, i) => {
    // delay each request by 400ms to avoid hitting the limit of 3 requests per second
    const ms = i * 400;
    return bingWebSearch(s.suggestion.replace(/\s/g, "+"), ms);
  });

  const res = await Promise.all(requests);

  suggestions.forEach((s, i) => {
    s.webpage = res[i];
    console.log(`n${i + 1}. ${s.suggestion} | times suggested: ${s.rank} | url: ${s.webpage}`);
  });
}

(function () {
  load();
})();

我重构bingWebSearch了一下,只返回结果,而不是直接更改建议列表。尝试在没有外部依赖的情况下尽可能保持函数自包含。

于 2021-04-26T23:43:59.640 回答