我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我喜欢Async/Await在Typescript等中提供的新功能的平坦性.但是,我不确定我喜欢这样一个事实,即我必须await在try...catch块的外部声明变量才能在以后使用它.像这样:
let createdUser
try {
createdUser = await this.User.create(userInfo)
} catch (error) {
console.error(error)
}
console.log(createdUser)
// business
// logic
// goes
// here
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我,但似乎最好不要在机构中放置多行业务逻辑try,所以我只留下createdUser在块外声明,在块中分配它的替代方案,以及然后用它.
在这种情况下,最佳做法是什么?
我正在尝试一些非常简单的事情:
如此简单,但我无法让它发挥作用。这是代码:
const playwright = require('playwright');
(async () => {
for (const browserType of ['chromium', 'firefox', 'webkit']) {
const browser = await playwright[browserType].launch();
try {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://google.com');
await page.fill('input[name=q]', 'cheese');
await page.press('input[name=q]', 'Enter');
await page.waitForNavigation();
page.waitForSelector('div#rso h3')
.then(firstResult => console.log(`${browserType}: ${firstResult.textContent()}`))
.catch(error => console.error(`Waiting for result: ${error}`));
} catch(error) {
console.error(`Trying to run test on ${browserType}: ${error}`);
} finally {
await browser.close();
}
}
})(); …Run Code Online (Sandbox Code Playgroud) 在ES6中是否可以在严格模式下try{}使用变量const?
'use strict';
const path = require('path');
try
{
const configPath = path.resolve(process.cwd(), config);
}
catch(error)
{
//.....
}
console.log(configPath);
Run Code Online (Sandbox Code Playgroud)
这不能lint因为configPath在范围之外定义.这似乎有用的唯一方法是:
'use strict';
const path = require('path');
let configPath;
try
{
configPath = path.resolve(process.cwd(), config);
} catch(error)
{
//.....
}
console.log(configPath);
Run Code Online (Sandbox Code Playgroud)
基本上,无论如何使用const而不是let这种情况?
我正在尝试使用此代码使用 puppeteer 从网站获取响应正文。
#!/usr/bin/env node
require('dotenv').config();
const puppeteer = require('puppeteer');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const path = require('path');
const fs = require('fs');
//
console.log('Starting Puppeteer...');
let responseBody = [];
(async () => {
const browser = await puppeteer.launch({
headless: false,
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
});
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', (request) => {
request.continue();
});
//
page.on('requestfinished', async (request) => {
const response = await request.response();
const url = response.url();
// store …Run Code Online (Sandbox Code Playgroud) 我刚刚开始在我的应用程序上使用 aws-sdk 将文件上传到 S3,我正在争论是否使用 aws-sdk v2 还是 v3。
V2 是整个包,考虑到我只需要 s3 服务,而不是无数其他选项,它非常臃肿。然而,文档非常神秘,我很难让等效的 getSignedUrl 函数在 v3 中工作。
在 v2 中,我有这个代码来签署 url,它工作正常。我在服务器上使用express
import aws from 'aws-sdk';
const signS3URL = (req,res,next) => {
const s3 = new aws.S3({region:'us-east-2'});
const {fileName,fileType} = req.query;
const s3Params = {
Bucket : process.env.S3_BUCKET,
Key : fileName,
ContentType:fileType,
Expires: 60,
};
s3.getSignedUrl('putObject',s3Params,(err,data)=>{
if(err){
next(err);
}
res.json(data);
});
}
Run Code Online (Sandbox Code Playgroud)
现在我一直在阅读文档和示例,试图让 v3 等效工作,但我找不到任何如何使用它的工作示例。到目前为止我的设置方式如下
import {S3Client,PutObjectCommand} from '@aws-sdk/client-s3';
import {getSignedUrl} from '@aws-sdk/s3-request-presigner';
export const signS3URL = async(req,res,next) => {
console.log('Sign')
const …Run Code Online (Sandbox Code Playgroud) 我正在研究一个Angular 6应用程序,我被告知以下是一个反模式:
await someFunction().then(result => {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
我意识到等待承诺链是毫无意义的.如果someFunction()返回一个promise,那么如果你正在等待它,则不需要一个promise链.你可以这样做:
const result = await someFunction();
console.log(result);
Run Code Online (Sandbox Code Playgroud)
但我被告知等待一个承诺链可能会导致错误,或者它会破坏我的代码中的东西.如果上面的第一个代码片段与第二个代码段完全相同,那么使用哪个代码片段至关重要.第一个片段引入了哪个危险,第二个片段没有?
我想知道 await 和 .then 是否可以在同一个异步函数中使用?这是我的功能:
uploadImageToImgur: async function (file) {
return new Promise(function(resolve, reject) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my auth',
},
body: result.replace(/^data:image\/(png|jpg|jpeg|gif);base64,/, "")
})
.then((response) => {
response.json()
.then(data => {
resolve(data.data.link)
})
});
} catch (e) {
reject(e);
}
}
});
},
Run Code Online (Sandbox Code Playgroud)
然后我在另一个函数中调用这个函数,在那里我使用我从 …
我对这两个代码块的差异感兴趣。
const $anchor = await page.$('a.buy-now');
const link = await $anchor.getProperty('href');
await $anchor.click();
Run Code Online (Sandbox Code Playgroud)
await page.evaluate(() => {
const $anchor = document.querySelector('a.buy-now');
const text = $anchor.href;
$anchor.click();
});
Run Code Online (Sandbox Code Playgroud)
通常,我发现原始DOM元素page.evaluate()更易于使用,而$方法返回的ElementHandles是到目前为止的抽象。
但是我也许觉得异步Puppeteer方法可能更高效或更可靠?我在文档中找不到关于此的任何指导,并且有兴趣了解有关每种方法的专业人士/专业人士以及添加诸如之类的方法背后的动机的更多信息page.$$()。
javascript ×8
node.js ×6
promise ×4
async-await ×3
puppeteer ×2
try-catch ×2
amazon-s3 ×1
asynchronous ×1
aws-sdk-js ×1
bluebird ×1
ecmascript-6 ×1
es6-promise ×1
fs ×1
playwright ×1
scope ×1