SegmentFault await-async的问题
2024-03-12T01:40:56+08:00
https://segmentfault.com/feeds/tag/await-async
https://creativecommons.org/licenses/by-nc-nd/4.0/
Python await 函数执行顺序的问题?
https://segmentfault.com/q/1010000044703219
2024-03-12T01:40:56+08:00
2024-03-12T01:40:56+08:00
从君华
https://segmentfault.com/u/congjunhua
-1
<p>下面这段代码中,为何 <code>ws.send_text("1")</code> 必须等待 <code>load_dataset("beans")</code> 加载完毕才会执行呢?</p><p>不应该是先执行 <code>ws.send_text("1")</code> 然后再执行 <code>load_dataset("beans")</code> 吗?</p><blockquote><code>load_dataset</code> 是一个<a href="https://link.segmentfault.com/?enc=Ws%2Fqe6lYwrmVw6U%2F9H%2BDbg%3D%3D.%2Fwf66Ew7oZt75phVjPVEmIpNlG%2FH6Bo6vB83TZ76tDmrgYpPLf0GhfGmxPGcELyOQSUHijMyKwYRkwQNzcsJW38AdvAWEKqEz17U28H7W2j2DcSUqUbGGHI9rYfr6Tnt" rel="nofollow">加载模型数据集的函数</a>。</blockquote><pre><code class="python">from fastapi import FastAPI, WebSocket
from datasets import load_dataset
app = FastAPI()
@app.websocket("/")
async def h(ws: WebSocket):
await ws.accept()
await ws.send_text("1")
dataset = load_dataset("beans")
await ws.send_text("2")</code></pre>
js async await真没看出哪有问题?
https://segmentfault.com/q/1010000043410671
2023-02-10T16:30:34+08:00
2023-02-10T16:30:34+08:00
寅春树
https://segmentfault.com/u/chunshu
0
<p>下面的代码提示错误:看了半天真没看出有什么错误。<br><img src="/img/bVc6jga" alt="image.png" title="image.png"></p><pre><code><script setup lang="ts">
省略。。。
const getTopData = async () => {
console.log("进来了")
const res=await analyseApi.getTopData(data.topFilter).catch(e=>{
ElMessage.error(e)
})
。。。
}
const getAllApi = async () => {
await Promise.all([getRightOne(),getRightThree(),getTopData()])
}
onMounted(async ()=>{
await getAllApi()
})
</code></pre>
vue typescript 封装 await 组件/指令
https://segmentfault.com/q/1010000042083565
2022-07-07T20:45:01+08:00
2022-07-07T20:45:01+08:00
ForkKILLET
https://segmentfault.com/u/forkkillet
0
<p>今天觉得 <code><Suspense></code> 不太方便,每次使用都要单独编写一个异步组件</p><p>于是想封装一个流程:对于任意一个 <code>Promise</code>,在它的 <code>pending</code>, <code>fulfilled</code> 和 <code>rejected</code> 状态显示不同的内容,其中</p><ul><li>在 <code>fulfilled</code> 状态,这块内容的模板中,应该能访问到 result</li><li>在 <code>rejected</code> 状态,应该能访问到 error</li></ul><hr><p>为什么不想使用 <code><Suspense></code>:<br><code>Promise</code> 不一定是组件内部产生的,为了一个 <code>Promise</code> 单独写一个异步组件有些麻烦,最好能把这个逻辑抽象出来</p><hr><p>我的尝试:<br>然后我就想着封装成一个组件,传入三个 slot 就行:</p><pre><code class="vue"><script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
value?: Promise<any>
}>()
const state = ref<'pending' | 'fulfilled' | 'rejected'>('pending')
const result = ref()
const error = ref()
props.value?.then(
(r) => {
result.value = r
console.log(result)
state.value = 'fulfilled'
},
(e) => {
error.value = e
state.value = 'rejected'
}
)
</script>
<template>
<slot v-if="state === 'pending'" name="first"></slot>
<slot v-if="state === 'fulfilled'" name="then" :result="result"></slot>
<slot v-if="state === 'rejected'" name="catch" :error="error"></slot>
</template></code></pre><p>用例:</p><pre><code class="vue"><script setup lang="ts">
interface AsyncData {
text: string
}
async function getAsyncData(): AsyncData {
return { text: 'test' }
}
</script>
<template>
<Await :value="getAsyncData()">
<template #first>Loading...</template>
<template #then="{ result }">
{{
/* @ts-expect-error */
result.text // result 类型丢了
}}
</template>
</Await>
</template></code></pre><ul><li>这个实现用了 <code>Promise<any></code>,所以 <code>v-slot</code> 里面类型就丢了</li><li>项目没有使用 tsx,用不了泛型组件;利用 class 能实现泛型组件,但还是会丢 <code>v-slot</code> 类型(参考 <a href="https://link.segmentfault.com/?enc=sgVme507lcqCuSM4ox4rEA%3D%3D.y88trRLei8pjmt2v0yevAVPmkfJFrsO5JHwYSZMA4VxEH626wa57cs91ZrPBeyxk" rel="nofollow">vuejs/core #3102</a>)</li></ul><hr><p>然后我就想着能不能封装成指令,像 <a href="https://link.segmentfault.com/?enc=otCb7nZvddQiOCfAsiDsHA%3D%3D.JUs7BrtVVwwdbSLCLt1vo7jO4t5DFBOhUyOLQ8qhXXqfSmI%2ByRD14FjS%2BKunxczG" rel="nofollow">svelte</a> 那样</p><pre><code class="svelte">{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}</code></pre><p>转写下来可能长这样:</p><pre><code class="vue"><p v-await="promise">...waiting</p>
<p v-then="number">The number is {{ number }}</p>
<p v-catch="error" style="color: red">{{ error.message }}</p></code></pre><p>尝试写的时候我遇到了一些疑惑:</p><ol><li>这三个自定义指令要连起来使用,和 <code>v-if / v-else-if / v-else</code> 有点像,然后我看了看 <code>v-if</code> 的<a href="https://link.segmentfault.com/?enc=1ua5r0mJQbfFEqYiVH9WLg%3D%3D.WrD2RfcWL9%2BcppgdgkIIbi01popjEnoktF6xJvO572lNLgm%2BmzJiV8mJChNMHRf34%2FDJK6ieIixzBLFT6CRTJ5MBZb%2B5%2F%2B96dVLPc5wVRjhOh6o6C69ctY8wsCoH3HTa" rel="nofollow">源码</a>,是要定义在一起,然后就搞不懂了!有没有稍微通俗一点的讲解呢</li><li>有些怀疑这些指令写出来 vscode 认不认识,Volar 里面 vue 自带指令的类型推导是不是单独写的?</li></ol><hr><p>总结提问:</p><ul><li>不用 tsx,用组件实现是否是可行的?</li><li>vue 指令的教程?</li><li>Volar 对带指令模板中类型的处理?</li></ul>
请教下await和async的理解问题
https://segmentfault.com/q/1010000041809009
2022-05-07T16:09:33+08:00
2022-05-07T16:09:33+08:00
不懂就问总不会错
https://segmentfault.com/u/studyphp
0
<pre><code>async function testResult() {
let first = await doubleAfter2seconds(30);
let second = await doubleAfter2seconds(50);
let third = await doubleAfter2seconds(30);
console.log(first + second + third);
}
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
} )
}
function a(){
console.log(1)
}
a()
testResult()
console.log('success')</code></pre><p>百度后看到这么一段代码<br>async是将方法异步处理<br>await是等待方法执行成功后再执行下面的代码,相当于抵消了async的作用?<br>(这两个是这么理解吗)</p><hr><p>我今天看到个这种写法,这种有什么作用呢?求大佬解惑</p><pre><code>await this.getConfig()
async getConfig() {
var res = await this.$get('server/paotui/getconfigbyuid')
if (res.errcode != 0) {
this.$toast(res.errmsg);
return;
}
this.feeOptions = res.config.xiaofei
},</code></pre>
Promise如果一直没有resolve,await会一直等待吗?
https://segmentfault.com/q/1010000037677124
2020-10-31T12:08:41+08:00
2020-10-31T12:08:41+08:00
greendev
https://segmentfault.com/u/greendev
0
<p>代码如下,这种情况,是不是程序一直都在等待。</p><pre><code class="javascript">function foo(x) {
return new Promise((resolve) => {
if (x > 1) {
resolve(11)
}
})
}
async function test() {
let a = await foo(0)
alert(a)
}
test()</code></pre>
为什么for中使用 await ,循环结束后不再执行 for 下面的代码?
https://segmentfault.com/q/1010000030686937
2020-10-08T15:15:32+08:00
2020-10-08T15:15:32+08:00
FlexUI
https://segmentfault.com/u/jinganglang
0
<p>我在循环中使用了 await 但是for结束后不再执行 下面的代码了,如何解决??</p><pre><code>var onloadend = async (res)=>{
var m3u8 = '';
let data = res.target.result.split('\n');
for(let i = 0; i < data.length; i++){
if(data[i].indexOf("#") == -1){
let tsUrl = data[i];
let down = await ts_down(tsUrl);
m3u8 += down +`\n`
}else{
m3u8 += data[i] +`\n`
}
};
//下面不再执行了
console.log('不再执行了')
};
function ts_down (url){
return new Promise((resolve,reject)=>{
uni.downloadFile({
url: url,
success: (res) => {
if (res.statusCode === 200) {
//下载成功了
resolve(s.savedFilePath);
}
}
});
})
}</code></pre>
await 一个递归函数怎么才能正确执行 ?
https://segmentfault.com/q/1010000023186579
2020-07-11T18:18:25+08:00
2020-07-11T18:18:25+08:00
末子
https://segmentfault.com/u/mozi_59256b4dc0e66
0
<pre><code>preUpload: async function (e) {
……
await the.multiUpload({
path: pics
})
console.log('upload result: ', data)
}</code></pre>
<pre><code>multiUpload: async function (data) {
……
if (i < data.path.length) {
multiUpload(data) //递归,回调自己
} else {
wx.hideLoading()
}
……
}</code></pre>
<p>当前 multiUpload 没有执行完,就输出 upload result 了</p>
<p>由于是递归,不清楚 promise 应该写在哪 … 试着将 resolve 写道 else 中,结果并没有执行 …</p>
js异步同步问题
https://segmentfault.com/q/1010000022565936
2020-05-07T11:43:18+08:00
2020-05-07T11:43:18+08:00
放心奶
https://segmentfault.com/u/fangxinnai
0
<p>在微信小程序中遇到了异步转同步的问题,代码如下:</p>
<pre><code class="javascript">checkUserState(){
var _this=this;
wx.cloud.callFunction({
name: 'getUserOpenInfo',
success: async res=>{
var userOpenId=res.result.event.userInfo.openId;
console.log("已获取到用户信息:"+JSON.stringify(res.result.event.userInfo));
_this.data.userInfo.openId=userOpenId;
if(await Util.userExit(userOpenId)){
_this.data.messageInfo=Util.pullMessageInfo(userOpenId);
}
else{
await Util.addUser(_this.data.userInfo);
}
console.log("我是分割线");
_this.setData({
userInfo:_this.data.userInfo,
messageInfo:_this.data.messageInfo,
pullMessageComplete:true,
})
},
})
},</code></pre>
<p>我大概解释一下代码:<br><img src="/img/bVbGQyz" alt="CleanShot 2020-05-07 at 11.27.56@2x.png" title="CleanShot 2020-05-07 at 11.27.56@2x.png"></p>
<p>遇到的问题:获取到openid后,在success回调中应当先执行<code>Util.userExit(userOpenId)</code>方法判断用户在数据库中是否存在,然后执行<code>Util.pullMessageInfo</code>/<code>Util.addUser</code>。最后执行<code>_this.setData</code>。</p>
<p>但是现在的情况时,加上await和不加没什么区别,方法的执行是乱的。<br><img src="/img/bVbGQAn" alt="CleanShot 2020-05-07 at 11.41.02@2x.png" title="CleanShot 2020-05-07 at 11.41.02@2x.png"></p>
<p>怎么才能让上述异步方法转同步呢,等待异步方法执行完毕呢。</p>
请教一个关于 数据库操作函数 await promise同步的问题?
https://segmentfault.com/q/1010000022537100
2020-05-03T18:56:32+08:00
2020-05-03T18:56:32+08:00
sean
https://segmentfault.com/u/darkblue5
0
<p>请教一个关于数据库操作进行同步问题。</p>
<p>问题的背景是要作一系列用户登陆操作,希望能达到根据用户 openID检索用户数据库,有则用库中的用户个人信息初始化接下来的函数,没有则要填入一个基本信息字段后,新增这个用户。</p>
<p>很显然这里的数据库访问 get 跟 新增 add等都是属于异步函数,要进行同步,尤其是新增用户,要选录入一个 信息,再做数据库 add</p>
<p>我个人的习惯是先做一个小demo,将同步机制完成后,再并入 实际的程序中。</p>
<p>然而读了几天官方手册,也看了不少网上的贴子,尝试了3种方式,进行同步,都没能实再想要的效果。</p>
<p>恳请过路的高人前辈帮忙瞅一瞅,应该怎样解决同步的问题。</p>
<p>先上demo中 index.js的代码</p>
<pre><code>//index.js
const regeneratorRuntime = require("../../libs/regeneratorRuntime.js");
const promisify = require('../../libs/promisify.js');
const app = getApp();
const db = wx.cloud.database();
Page({
data: {
grade: 0,
innerData: 0
},
onLoad: function () {
let that = this;
console.log('initical data', that.data.innerData);
// const awfun4 = promisify(that.fun4());
// const awfun5 = promisify(that.fun5());
// const awfun6 = promisify(that.fun6());
that.orderTest();
// console.log(awfun4);
// console.log(awfun5);
// console.log(awfun6);
},
orderTest: async function () {
let that = this;
await that.fun4();
console.log('after fun1', that.data.innerData);
await that.fun5();
console.log('after fun2', that.data.innerData);
await that.fun6();
console.log('after fun3', athat.data.innerData);
await that.fun4();
console.log('after fun1', that.data.innerData);
await that.fun5();
console.log('after fun2', that.data.innerData);
await that.fun6();
console.log('after fun3', that.data.innerData);
await that.fun4();
console.log('after fun1', that.data.innerData);
await that.fun5();
console.log('after fun2', that.data.innerData);
await that.fun6();
console.log('after fun3', that.data.innerData);
},
fun1: function () {
let that = this;
that.data.innerData = that.data.innerData + 1;
console.log('in fun1, innerData', that.data.innerData);
return 0;
},
fun2: function () {
let that = this;
that.data.innerData = that.data.innerData + 2;
that.data.grade = 4;
console.log('in fun2, innerData', that.data.innerData);
return 0;
},
fun3: function () {
let that = this;
that.data.innerData = that.data.innerData + 3;
console.log('in fun3, innerData', that.data.innerData);
return 0;
},
fun4: function () {
let that = this;
// return new Promise((resolve, reject) => {
db.collection('rank').where({
uid: "asdfaf"
}).get().then((res) => {
//success: res => {
that.fun1();
//}, fail: err => {
//that.fun1();
//}
});
//return promise;
},
fun5: function () {
let that = this;
db.collection('rank').where({
uid: "asdfaf"
}).get().then((res) => {
that.fun2();
});
return 0;
},
fun6: function () {
let that = this;
db.collection('rank').where({
uid: "asdfaf"
}).get().then((res) => {
that.fun3();
});
},
})
</code></pre>
<p>简单做一下解释,有三个基本的同步函数 fun1, fun2, fun3里边操作一个变量 innerData 作自增, 因为是要做异步操作的同步,所以在 fun4, fun5, fun6中分别加入一段带 where条件的数据库访问函数,如果成功则调用刚才fun1, fun2, fun3。</p>
<p>为了进行同步判断,在调用一列系待同步函数 fun4,fun5,fun5中,console.log打印出 当前的做测试的 innerData,跟函数名称, 在调用 fun4,fun5,fun6后也打印 innerData跟函数名,判断是否正确同步。</p>
<p>事实的输出结果有两处跟预期不相符。</p>
<p>第1是 主程序中所有的console.log是一齐打到终端的,并且,值也是 innerData的初始值,没有被fun1,fun2, fun3操作自增,</p>
<p>是不是console.log本身也是异步的,网上看了一贴子不是太理解,个人理解贴子表达的意思是不是说跟缓存有关?</p>
<p>第2个更关键的是,我用了网上能查到的 3种方式,尝试同步 带数据库操作的 fun4,fun5,fun6,但都没有能正确实再 顺序同步。</p>
<p>分别是</p>
<p>1、主程序 async,fun4,fun5,fun6前加await</p>
<p>2、使用promise方法,封装生成一个 promise对象</p>
<p>3、import第3方promisify库,封装fun4,fun5,fun6代码</p>
<p>都没能达到预期效果,输出始终不同步</p>
<p><img src="/img/bVbGI5F" alt="0.png" title="0.png"><br>请问我的3种实现方式,主要问题在哪里,应该怎样正确实现同步?</p>
<p>项目配置如下<br><img src="/img/bVbGI5G" alt="0 (1).png" title="0 (1).png"></p>
如何用vue写一个方法,按顺序同步执行?
https://segmentfault.com/q/1010000021851434
2020-02-27T09:56:57+08:00
2020-02-27T09:56:57+08:00
kirin
https://segmentfault.com/u/kirin0918
0
<p>现有一个需求,在class上动态添加animate.css的class值,比如第一分钟“fade animated”,第二分钟执行“bounce animated”,以此类推,想写一个方法实现,不知道怎么实现?</p>
await如何并行执行?
https://segmentfault.com/q/1010000021804783
2020-02-21T17:31:43+08:00
2020-02-21T17:31:43+08:00
simple_5820793e901a0
https://segmentfault.com/u/simple_5820793e901a0
2
<p>问题:先统一生成promise实例后,为哈就能同步执行了</p>
<pre><code>function getName () {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve('tony')
}, 2000)
})
}
function getId () {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve('123')
}, 3000)
})
}
(async ()=>{
let name = await getName(); // 需要2s
let id = await getId(); // 等待getName()执行后才能执行,执行需要3s
alert(`name:${name}, id:${id}`); // 大概5秒
})();
(async ()=>{
// 先 生成promise实例,下面两个行代码同步执行,无需等待
let namePromise = getName();
let idPromise = getId();
// 为啥下面就能同步执行了
let name = await namePromise;
let id = await idPromise;
alert(`name:${name}, id:${id}`); // 大概3秒
})()</code></pre>
await为什么可以直接在console使用?
https://segmentfault.com/q/1010000021780693
2020-02-18T22:29:17+08:00
2020-02-18T22:29:17+08:00
wolfan
https://segmentfault.com/u/wolfan
0
<p><code>const a= await fetch(url).then(r=>{return r.json()});</code><br>为什么可以直接在console中执行成功,但是放到js文件中却需要丢进async function() 中去?</p>
<p>而且在console中上面这段返回的是直接的数据,但是在async的返回中却是个promise。那要怎么才让fetch()返回数据给a呐?</p>
关于async/await promise 执行顺序
https://segmentfault.com/q/1010000021628640
2020-01-20T14:02:20+08:00
2020-01-20T14:02:20+08:00
哈哈哈1212
https://segmentfault.com/u/hahaha1212
0
<pre><code> function doA1(){
new Promise( function (resolve) {
console.log(11);
resolve();
}).then(o=>{
console.log(12);
}).then(o=>{
console.log(13);
}).then(o=>{
console.log(14);
})
}
await doA1();
console.log(2);
//执行结果顺序为 11 12 2 13 14 </code></pre>
<pre><code> function doA1(){
return new Promise( function (resolve) {
console.log(11);
resolve();
}).then(o=>{
console.log(12);
}).then(o=>{
console.log(13);
}).then(o=>{
console.log(14);
})
}
await doA1();
console.log(2);
//执行结果顺序为 11 12 13 14 2</code></pre>
<p>请高手解释下为何会如此执行 特别是第一段代码 执行结果为什么不是 11 2 12 13 14</p>
在 Koa 的路由中使用 await 会造成阻塞吗?
https://segmentfault.com/q/1010000020803402
2019-10-25T22:44:47+08:00
2019-10-25T22:44:47+08:00
illusion
https://segmentfault.com/u/________________
1
<p>看过一篇文章说在 nodejs koa 的路由中使用await语法不会造成阻塞,但我测试了一下结果却不是这样,代码:<br><img src="/img/bVbzr4n?w=1334&h=1090" alt="image.png" title="image.png"></p>
<p>浏览器测试,在浏览器同时打开两个标签页,以最快手速刷新两个页面,结果:</p>
<p><strong>标签页一</strong><br><img src="/img/bVbzr4s?w=1486&h=738" alt="image.png" title="image.png"></p>
<p><strong>标签页二</strong><br><img src="/img/bVbzr4u?w=1402&h=712" alt="image.png" title="image.png"></p>
<hr>
<p>标签页二 9.2s 是因为手动刷新的页面。</p>
<p>以上是用chrome测试的,<br>后来用safari测试结果是非阻塞的,为啥</p>
封装一个obj对象 实现 obj 链式调用,异步等待settimeOut之后继续调用
https://segmentfault.com/q/1010000017938480
2019-01-18T11:09:11+08:00
2019-01-18T11:09:11+08:00
Jogen
https://segmentfault.com/u/jogen
1
<p>例:<br>obj.write("1").await(1000).write("2");<br>// 打印 1<br>// 等待 await 时长之后打印 2### 题目描述</p>
python 异步协程的实现
https://segmentfault.com/q/1010000015881317
2018-08-04T00:01:24+08:00
2018-08-04T00:01:24+08:00
xu_zhoufeng
https://segmentfault.com/u/inside
0
<p>需要对一个上百万行的json文件进行清洗,并需要将清洗好的结构化数据重新存储为csv文件。尝试使用pandas的dataframe转存清洗好的数据条目,却发现常规的清洗一条写入一条的速度太慢了,速度主要卡在每次数据的写入,于是为此专门定义了一个 asyn writeline,同时利用 async readline 每次生成 100 个协程处理100行数据,然而测试结果却和常规的按序处理无差别,平均每条数据处理速度都在 0.5 s 左右,感觉是自己的 asyn writeline 有问题,还请大神赐教。</p>
<p>测试代码如下:</p>
<pre><code>import pandas as pd
import json
import time
import asyncio
def trop():
tropicos = pd.DataFrame()
with open(r"/tropicosbase.json", "r") as yn:
count = 0
tropicos['tag'] = None
tropicos.loc[0] = None
async def readline(line):
nonlocal count
js = json.loads(line)
await writeline(js, tropicos, count)
count += 1
tropicos.loc[count] = None
cs = yn.readlines()[:100]
tasks = [asyncio.ensure_future(readline(line)) for line in cs]
loop = asyncio.get_event_loop()
start = time.time()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print(end - start)
tropicos.to_csv(r'/tropicos.csv', index=None)
async def writeline(js, tropicos, count):
for k, v in js.items():
try:
tropicos[k][count] = v
except KeyError:
if k == 'detailsdiv':
pass
else:
tropicos[k] = pd.Series()
tropicos[k][count] = v
trop()</code></pre>
奇怪的 Unhandled promise rejection
https://segmentfault.com/q/1010000014866742
2018-05-15T14:55:55+08:00
2018-05-15T14:55:55+08:00
brook
https://segmentfault.com/u/brook
0
<p>如下代码,一直输出<code>Unhandled promise rejection (rejection id: 1): error1</code>,怎么避免?</p>
<p>主要功能为 getVal 第一次调用预加载,第二次调用时没返回就等,返回了就直接取值</p>
<pre><code class="js">const rejects = [0,1]
let i = 0
function getSummary( id) {
return new Promise((resolve, reject) => {
console.log('rr', id, i)
if(rejects.includes(i)) {
setTimeout(() => reject('error1'), 200)
} else if(id === 1) {
setTimeout(() => resolve(id), 200)
} else {
setTimeout(() => resolve(id), 500)
}
i++
})
}
class Test {
test() {
this.getVal()
setTimeout(async () => {
try {
const val = await this.getVal()
console.log('get1', val)
}catch (ex) {
console.log('error')
}
console.log('get2', await this.getVal())
}, 1000)
}
async getVal() {
try {
if (!this.summary) {
this.summary = getSummary(1).catch(() => getSummary(2)).then((data) => {
this.summary = data
return data
})
} else if(this.summary.then) {
return await this.summary
}
} catch (ex) {
this.summary = null
}
return this.summary
}
}
new Test().test()</code></pre>
<hr>
<p><strong>已解决见3楼</strong><br>如1楼所说,第一个 getVal 异常被上抛了,直接 try catch 也不行,只能 Await 才行。<br>只好去看 await 改成3楼的了</p>
eggjs中controller调用service方法,加或不加await的区别是什么?
https://segmentfault.com/q/1010000015549058
2018-07-06T12:17:50+08:00
2018-07-06T12:17:50+08:00
chanmmufeng
https://segmentfault.com/u/chanmmufeng
0
<p>//test/service/role.js service代码如下</p>
<pre><code>async deleteRoleById(id){
const{app} = this;
try {
await conn.delete('role', {
id: id,
});
} catch (error) {
return false;
}
return true;
}</code></pre>
<p>//test/controller/role.js controller代码如下</p>
<pre><code> async roleDeleteDo(){
const{ctx} = this;
const ids_str = ctx.request.body.ids_str;
//await 加或不加??
const result = await ctx.service.role.deleteRolesByIds(ids_str);
console.log(result);
if (result){
//返回操作正确的提示
ctx.body = ctx.ResultUtil.success();
}else{
//返回错误操作的提示
ctx.body = ctx.ResultUtil.error(config.werror.ERR_ROLE_DELETE);
}
return;
}</code></pre>
<p>当controller利用 <code>await ctx.service.role.deleteRolesByIds(ids_str)</code> 调用service时,<code>console.log(result);</code>的打印结果为true或者false,而如果不加 <code>await</code>,打印结果则为 <code>Promise {true(或false)}</code></p>
<p>我知道async函数返回结果是一个Promise对象,而且程序的目的(删除role)也确实达到了,但是有疑问如下:</p>
<ol>
<li>如果不加<code>await</code>,我能否直接用if来判断result是否为<code>true</code>或者<code>false</code>
</li>
<li>既然都达到了最终的目的(或者说不加await操作有潜在隐患,而我并不清楚这一点),那为什么还要加await,意义是什么? ps:官方文档是加await的</li>
<li>既然是异步操作,为什么js不会首先执行<code>console.log</code>函数,而会等到await执行完了才会执行,看起来相当于后面的操作被阻塞住了</li>
</ol>
<p>希望各位不吝赐教,小弟由衷感谢</p>
怎样使用aiohttp请求多个url
https://segmentfault.com/q/1010000015443694
2018-07-01T23:53:28+08:00
2018-07-01T23:53:28+08:00
用户bPt2ky
https://segmentfault.com/u/361
0
<p>这是aiohttp官方请求单个url的方式,如果请求多个url并获取内容应该怎么做?</p>
<pre><code>import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())</code></pre>
腾讯云 wafer2 使用knex 问题
https://segmentfault.com/q/1010000015234640
2018-06-09T11:53:15+08:00
2018-06-09T11:53:15+08:00
独自等待
https://segmentfault.com/u/duzidengdai_5ad3fb2e60f90
0
<p>使用wafer2 中的mysql语句插入数据报错 await is only valid in async function</p>
<p><img src="/img/bVbb5nZ?w=995&h=621" alt="图片描述" title="图片描述"></p>
<p>服务端报错:<br><img src="/img/bVbb5n3?w=713&h=436" alt="图片描述" title="图片描述"></p>
js实现异步队列传参?
https://segmentfault.com/q/1010000015199352
2018-06-06T13:27:32+08:00
2018-06-06T13:27:32+08:00
刀洒温柔
https://segmentfault.com/u/daosawenrou
0
<p>我有好几个异步的函数操作,但是希望这些异步的操作按顺序来执行,希望用到队列,并且每一个函数都需要传参。想到了koa2的中间件,但是实现的话需要怎么样实现呢?或者有没有其他的方法。<br>谢谢。</p>
Node.js Promise resolve
https://segmentfault.com/q/1010000013933773
2018-03-23T10:45:08+08:00
2018-03-23T10:45:08+08:00
Programer
https://segmentfault.com/u/loveqq
0
<p>在使用await async的时候,定义一个async函数:</p>
<pre><code>async updateUserInfo(objectId, username, mobilePhoneNumber, appId){
let replaceSql = `update xc_scm_leancloud_users set username="${username}",mobilePhoneNumber="${mobilePhoneNumber}" where objectId="${objectId}" and appId="${appId}"`;
scmSequelize.query(replaceSql);
}
调用:
updateUserInfo(objectId, username, mobilePhoneNumber, appId)
.catch(err => {
logger.error('leancloudUser afterUpdate err: ', err);
res.send(new XCResult(false, new XCError('', XC_BIZ_ERROR_TYPE.BIZ_ERROR,err)));
return next();
});
在updateUserInfo()中没有返回值的时候,整个服务器的内存占用为90M左右,在updateUserInfo()中加上返回值:
async updateUserInfo(objectId, username, mobilePhoneNumber, appId){
let replaceSql = `update xc_scm_leancloud_users set username="${username}",mobilePhoneNumber="${mobilePhoneNumber}" where objectId="${objectId}" and appId="${appId}"`;
return scmSequelize.query(replaceSql);
}
</code></pre>
<p>服务器的内存占用为140M+,这是怎样产生的?我想问一下promise的resolve和reject对内存的影响是什么?怎样影响的?</p>
async await 并发执行的问题
https://segmentfault.com/q/1010000013094828
2018-02-02T10:31:58+08:00
2018-02-02T10:31:58+08:00
Milu
https://segmentfault.com/u/milu
1
<pre><code>async sleep(i){
return new Promise((resolve, reject) => {
setTimeout(function (){
resolve(i);
}, 1000);
});
}
async start(finsh_callback){
console.time('g');
for (let i = 0; i < 5; i++) {
let res = await this.sleep({
i:i,
});
console.log(res);
}
console.timeEnd('g');
}
</code></pre>
<p>执行 start 函数<br>输出</p>
<pre><code>{ i: 0 }
{ i: 1 }
{ i: 2 }
{ i: 3 }
{ i: 4 }
g: 5003.286ms</code></pre>
<p>本来5个任务,如果异步同时进行,也就是1秒左右。<br>现在改成了async await 的写法之后,变成了一个接着一个进行,花费了5秒。如果我想多个并发执行,如何解决?</p>
es7 async await 为什么会对react setState起作用?
https://segmentfault.com/q/1010000012935197
2018-01-22T15:16:55+08:00
2018-01-22T15:16:55+08:00
邓不耙
https://segmentfault.com/u/dengbuba
5
<p>es7 async await 为什么会对react setState起作用?setState()并不是一个promise啊!?下面是代码和日志</p>
<pre><code>constructor(props){
super(props);
this.state={
value:this.props.value||this.props.defaultValue||'',
result:true,
}
}
verifier(){
let result;
let{rules} = this.props;
let{value} = this.state;
switch (this.rulesClassify()){
case 'fn' :
result = rules();
break;
case 'reg' :
result = rules.test(value);
break;
default :
result = rules===value;
}
this.setState({
result
});
}
/*
**
@每次变动callback
*/
async handleChange(event){
//受控
let value=event.target.value;
await this.setState({
value
});
debug(this.state.result);
//验证
await this.verifier();
debug(this.state.result);
}</code></pre>
<p><img src="/img/bV2q8U?w=1436&h=146" alt="图片描述" title="图片描述"></p>
<p>这里验证了input中只能是存数字,当我输入非数字时,如果没有使用 async和await的时候log就会输出两个true,而当使用async和await时,则是上图结果,说明async和await起了作用</p>
async/await中的promise返回错误reject的一个小疑问
https://segmentfault.com/q/1010000012275540
2017-12-04T15:55:00+08:00
2017-12-04T15:55:00+08:00
qz121085932
https://segmentfault.com/u/qz121085932
1
<p>最近在学 <code>node</code> ,之前对 <code>async/await</code> 和 <code>promise</code> 略懂,但不是很熟悉,大家都知道,<br><code>promise</code> 返回的 <code>resolve</code> 对象可能用 <code>await</code> 去接,最近在写代码的时候,突发奇想,既然 <code>resolve</code> 的代码 <code>await</code> 接收的到,那 <code>reject</code> 的呢,我觉得可能接收不到,随之我就试验了一下,果不其然,报错了,哈哈哈,那么疑问就随之而来了,那万一碰到 <code>reject</code> 的情况怎么办,岂不是很蛋疼,望大佬们多多指教一下, <code>thank you ~</code></p>
<p>国际惯例,贴个代码,贴个报错图吧</p>
<pre><code>let pro = function () {
return new Promise((resolve, reject) => {
reject('err')
})
}
let sync = async function(){
let awaitResult = await pro()
console.log(awaitResult)
}
sync()
</code></pre>
<p>图如下:<br><img src="/img/bVZFAG?w=2864&h=186" alt="图片描述" title="图片描述"></p>
await调用promise碰到一些问题,烦请看一看
https://segmentfault.com/q/1010000012256913
2017-12-02T21:44:15+08:00
2017-12-02T21:44:15+08:00
qz121085932
https://segmentfault.com/u/qz121085932
0
<p>国际惯例,先贴上代码</p>
<pre><code>let awaitToken = function (options){
return new Promise((resolve, reject) => {
request(options, function (err, res, body) {
if (res) {
resolve(JSON.parse(body));
} else {
reject(err);
}
});
})
}
let getAccessToken = function async (req,res,next) {
let queryParams = {
'grant_type': 'client_credential',
'appid': config.appId,
'secret': config.appSecret
};
let wxGetAccessTokenBaseUrl = 'https://api.weixin.qq.com/cgi-bin/token?' + qs.stringify(queryParams);
let options = {
method: 'GET',
url: wxGetAccessTokenBaseUrl
};
let result = await awaitToken(options)
if (result){
res.send(result)
}else{
res.send('something err')
}
};</code></pre>
<p>运行 这段代码运行不通,在<code>let result = await awaitToken(options) </code>处报错,报错如下图</p>
<p><img src="/img/bVZAKa?w=1102&h=476" alt="图片描述" title="图片描述"></p>
<p>上网查了一下,这个报错是语法错误,难道是没有找到<code>awaitToken</code>这个方法么,我觉得不太应该啊,还是说<code>await</code>没有接收到<code>awaitToken</code>返回回来的参数?还是说我这个<code>async-await</code>的使用方法错误???试了半天试不出来个结果,烦请帮忙看下,不胜感激~</p>
<p><code>node环境 7.6.0</code></p>