我是 NodeJS 新手,我有一个不明白的问题。
在此函数中,我依次调用多个 API 来检索有关电影的一些数据。结果并不总是一样。大多数时候,结果是正确的,但有时结果并不完整。
我尝试使用 then
尝试链接 API 调用,但似乎不起作用。
知道为什么结果并不总是相同吗?任何帮助将不胜感激。
// test fetchData(456165)
function fetchData(filmid) {
let average = array => array.reduce((a, b) => a + b) / array.length
var notes = []
mdb.movieInfo({
id: filmid,
language: 'fr'
},
(err, resOmdb) => {
notes.push(parseFloat(resOmdb.vote_average))
imdb
.getById(resOmdb.imdb_id, {
apiKey: 'e9d59b68',
timeout: 3000
})
.then(
allocine.api(
'search', {
q: `${resOmdb.title}`,
filter: 'movie'
},
function(error, resAllo) {
if (error) {
return
}
allocine.api(
'movie', {
code: `${resAllo.feed.movie[0].code}`
},
function(error, result) {
if (error) {
return
}
notes.push(parseFloat(result.movie.statistics.userRating) * 2)
}
)
// doesn't seem to execute all the time
allocine.api(
'showtimelist', {
zip: 44260,
movie: resAllo.feed.movie[0].code
},
function(error, resultCin) {
if (error) {
return
}
// sometimes doesn't appear in the result
resOmdb.cinemas = resultCin
}
)
}
)
)
.then(
function(result) {
notes.push(parseFloat(result.rating))
resOmdb.vote_average = average(notes).toFixed(2)
// check the result
console.log(util.inspect(resOmdb, false, null))
},
function(error) {
return
}
)
}
)
}
最佳答案
首先,您应该决定是否要使用 Promise。 如果这样做,请 promise 所有功能。接下来您需要做的就是“返回”您的 promise (如果它们在函数内部使用)。
在您的情况下,您的第一个 imbd api 调用可能不会返回。
接下来,您应该检查您的 Node 版本是否支持异步等待。
然后您就可以轻松地进行 API 调用,不受任何干扰。
'use strict';
const Promise = require('bluebird');
const mdb = Promise.promisfyAll(require('mdb'));
const allocine = Promise.pomisifyAll(require('allocine-api'));
// test fetchData(456165)
async function fetchDate(filmId) {
const notes = [];
const resOmdb = await mdb.movieInfoAsync({ id: filmId });
notes.push(parseFloat(resOmdb.vote_average));
const imdbResult = await imdb.getByIdAsync(resOmdb.imdb_id, { apiKey: 'e9d59b68', timeout: 3000 });
const resAllo = await allocine.apiAsync('search', { q: `${resOmdb.title}`, filter: 'movie' });
// and so on ...
}
更新:
为了加快您的功能,您可以同时执行请求。
为此,请使用 Promise.join
const [imdbResult, allocineResult] = await Promise.join(
imdb.getByIdAsync(resOmdb.imdb_id, { apiKey: 'e9d59b68', timeout: 3000 }),
allocine.apiAsync('search', { q: `${resOmdb.title}`, filter: 'movie' });
);
关于javascript - NodeJS返回的数据有时会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120301/