ise*_*maj 5 javascript asynchronous node.js
我最近询问了 javascript 中的异步,request-promise 模块返回 undefined。在有人提出相同的 SO 问题后,我非常理解它是如何从异步调用返回响应?. 我学到了很多东西,这有助于我如何正确地请求 api。但是现在我遇到了同样的问题,即使我async/await已经在使用。我把评论放在我得到的地方undefined。
const request = require('request');
const rp = require('request-promise');
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;
const CONNECTION_STRING = process.env.DB;
const dbName = 'fcc';
const connectionOption = { useNewUrlParser: true };
function StockHandler() {
this.latestWithoutLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
if (typeof lastPrice === 'string') {
getLikes(ticker, false, (data) => {
let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes
}
return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
if (typeof firstStockLastPrice === 'string' && typeof secondStockLastPrice === 'string') {
let firstStockLikes = await getLikes(ticker[0], false, (data) => { return data; });
let secondStockLikes = await getLikes(ticker[1], false, (data) => { return data; });
console.log(firstStockLikes); // <--- undefined
console.log(secondStockLikes); // <--- undefined
}
}
};
this.latestWithLike = async function(ticker, multipleStock, callback) {
if (!multipleStock) {
console.log('Single stock');
let lastPrice = await getLastPrice(ticker);
console.log(lastPrice);
if (typeof lastPrice === 'string') {
getLikes(ticker, true, (data) => {
let stockData = {
stock: data.stock,
price: lastPrice,
likes: data.likes + 1
}
return callback({ stockData: stockData });
});
}
} else {
console.log('Multiple stock');
let firstStockLastPrice = await getLastPrice(ticker[0]);
let secondStockLastPrice = await getLastPrice(ticker[1]);
console.log(firstStockLastPrice);
console.log(secondStockLastPrice);
}
};
}
function getLastPrice(ticker) {
let options = {
uri: `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker}&interval=1min&apikey=${process.env.ALPHA_KEY}`,
method: 'GET',
json: true
}
return rp(options)
.then(function(parsedBody){
let latestStockTradeTime = Object.keys(parsedBody[Object.keys(parsedBody)[1]])[0];
let closingPrice = parsedBody[Object.keys(parsedBody)[1]][latestStockTradeTime]['4. close'];
return closingPrice;
})
.catch(function(error){
return error;
})
}
function getLikes(ticker, likeStatus, callback) {
MongoClient.connect(CONNECTION_STRING, connectionOption, (err, client) => {
if (err) callback(err);
const db = client.db(dbName);
const collection = db.collection('stock');
if (!likeStatus) {
try {
collection.findOne(
{ stock: ticker.toUpperCase() },
{ upsert: true },
(err, result) => {
if (result === null) {
collection.insertOne(
{ stock: ticker.toUpperCase(), likes: 0 },
{ upsert: true },
(err, result) => {
return callback(result.ops[0]);
}
);
} else {
return callback(result);
}
}
);
} catch (e) {
return callback({ error: e });
}
}
else {
try {
collection.findOneAndUpdate(
{ stock: ticker.toUpperCase() },
{ $inc : { likes: 1 } },
{ upsert: true, new: true },
(err, data) => {
return callback(data.value);
}
);
} catch (e) {
return callback({ error: e });
}
}
});
};
module.exports = StockHandler;
Run Code Online (Sandbox Code Playgroud)
如果您要定义具有异步行为的函数,则可以使用async/await或 Promise 链接。在异步函数中,您可以使用await或链.then()来等待异步响应。您的函数向其调用者返回一个带有已解决值或错误的 Promise。
async function getLikes() {
const likes = await db.get('myLikes'); // this db method returns a Promise
// ...
return likes; // will return a Promise resolving likes from db or an error if there is one
}
async function logLikes() {
const result = await getLikes();
console.log(result);
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用一个异步函数并且不等待或像本例中那样链接响应......
async function getLikes() {
const likes = db.get('myLikes'); // uh oh, this is asynchronous
// ...
return likes;
}
Run Code Online (Sandbox Code Playgroud)
...在将返回值分配给 之前,线程可以继续前进like。那可能是您看到undefined问题的地方。
| 归档时间: |
|
| 查看次数: |
21599 次 |
| 最近记录: |