我有这个功能:
const upload = (example) => {
console.log('uploading...');
return new Promise(function (resolve, reject) {
resolve & reject
});
};
我在这里调用上面的函数:
const dirents = await fs.readdirSync(path, {withFileTypes:true});
await Promise.all(dirents.map(async (dirent) => {
await upload(example).then((response) => {
console.log('success');
}, (err) => {
console.log(err);
});
});
输出应为
'uploading' -> 'success' -> 'uploading' ...
但这实际上是
'uploading' -> 'uploading' -> 'success' -> 'success'
我也尝试过(for ... of
),但这对我也不起作用。
答案 0 :(得分:2)
对于顺序承诺,在public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.btn);
final Button button1 = findViewById(R.id.button2);
final Button button3 = findViewById(R.id.button3);
final TextView textView = findViewById(R.id.tex);
final EditText et1 = findViewById(R.id.et1);
final EditText et2 = findViewById(R.id.et2);
final Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
et1.setText("0");
et2.setText("0");
}
});
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
textView.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String value = et1.getText().toString();
int n11 = Integer.parseInt(value);
String value2 = et2.getText().toString();
int n22 = Integer.parseInt(value2);
textView.setText(String.valueOf(n22 + n11));
Toast.makeText(getApplicationContext(), "done ", Toast.LENGTH_SHORT).show();
}
});
}
}
函数中使用一个简单的循环非常清晰易读:
async
答案 1 :(得分:0)
这是一个将reduce
与async/ await
(可以运行here)一起使用的现代示例
let userIDs = [1,2,3];
userIDs.reduce( async (previousPromise, nextID) => {
await previousPromise;
return upload(nextID).then((val) => {
console.log("success", val);
})
}, Promise.resolve());
const upload = (id) => {
console.log('uploading...', id);
return new Promise(function (resolve, reject) {
resolve(id);
});
};
答案 2 :(得分:0)
**您还可以使用递归功能**
select checkin_date, count(pt_Id) as [Number of Patients Seen], 100*sum([esi 1 or 2])/count(pt_Id) as pct
from [Fast Track Quality Research v1]
group by checkin_date